package l1j.opqlo.Server;

import static l1j.server.server.model.skill.L1SkillId.加速器檢測;

import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldClan;
import l1j.server.server.datatables.lock.HellTimeReading;
import l1j.server.server.model.Getback;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.L1Party;
import l1j.server.server.model.L1Trade;
import l1j.server.server.model.Instance.L1DollInstance;
import l1j.server.server.model.Instance.L1FollowerInstance;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.model.Instance.L1SummonInstance;
import l1j.server.server.serverpackets.S_PacketBox;
import l1j.server.server.templates.L1HellTime;

public class QuitGame {

	private static Logger _log = Logger.getLogger(QuitGame.class.getName());

	/**
	 * 人物離開遊戲的處理
	 *
	 * @param pc
	 * @throws Exception
	 */

	public static void quitGame(final L1PcInstance pc) throws Exception {
		if (pc == null) {
			return;
		}
		if (pc.getOnlineStatus() == 0) {
			return;
		}
		if(pc.getHellTime() >0){
			final L1HellTime temp = HellTimeReading.get().getTempByObjid(pc.getId());
			if(temp ==null){
				HellTimeReading.get().BeginHell(pc.getId(), pc.getHellTime());
			}else{
				temp.setHellTime(pc.getHellTime());
			}
		}
		L1World.getInstance().putKillerId(pc.getId(), pc.getLastKillerId());
		final L1Trade trade = new L1Trade();
		trade.TradeCancel(pc);

		final L1Clan clan = WorldClan.get().getClan(pc.getClanname());
		if (clan != null) {
			if (clan.getWarehouseUsingChar() == pc.getId()) { // 使用血盟倉庫中
				clan.setWarehouseUsingChar(0); // 解除使用狀態
			}
		}
		try {
			pc.getNetConnection()._loc = pc.getLocation();
			if(pc.hasSkillEffect(加速器檢測)){
				pc.removeSkillEffect(加速器檢測);
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}

		// 離開組隊
		try {
			if (pc.isInParty()) { // 如果有組隊

				L1Party party = pc.getParty();
//				if (party == null && pc.getLogPartyId() > 0) {
//					party = TeamLog.getInstance().getPartyList(pc.getLogPartyId());
//				}
				if (party != null) {
					pc.getParty().leaveMember(pc);
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// TODO: 離開聊天組隊(?)
		try {
			if (pc.isInChatParty()) {// 如果在聊天組隊中(?)

				if (pc.getChatParty() != null) {
					pc.getChatParty().leaveMember(pc);
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// 移除世界地圖上的寵物
		// 變更召喚怪物的名稱

		if (!pc.getPetList().isEmpty()) {
			final Object[] petList = pc.getPetList().values().toArray();
			// 寵物 召喚獸 消除
			if (petList != null) {
				remove_pet(pc, petList);
			}
		}
		// TODO 重登刪除魔法娃娃
		try {
			if (!pc.getDollList().isEmpty()) {
				for (final L1DollInstance doll : pc.getDollList().getAllDolls()) {
					doll.deleteDoll();
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// TODO 重登刪除魔法娃娃
		// TODO 重登刪除跟隨
		try {
			if (!pc.getFollowerList().isEmpty()) {
				for (final L1FollowerInstance follower : pc.getFollowerList()
						.values()) {
					follower.setParalyzed(true);
					follower.spawn(follower.getNpcTemplate().get_npcId(),
							follower.getX(), follower.getY(),
							follower.getHeading(), follower.getMapId());
					follower.deleteMe();
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// TODO 重登刪除跟隨
		// 死亡狀態設置
		try {
			if (pc.isDead()) {
				final int[] loc = Getback.GetBack_Location(pc, true);
				pc.setX(loc[0]);
				pc.setY(loc[1]);
				pc.setMap((short) loc[2]);
				pc.setCurrentHp(pc.getLevel());
				if (pc.get_food() > 40) {
					pc.set_food(40);
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// 終止交易
		/*
		 * if (pc.getTradeID() != 0) { // トレード中 new L1Trade().TradeCancel(pc);
		 * }else{ L1Inventory inv = pc.getTradeWindowInventory(); final int
		 * player_tradecount = inv.getSize(); if(player_tradecount >0){
		 * List<L1ItemInstance> player_tradelist = inv.getItems(); for (int cnt
		 * = 0; cnt < player_tradecount; cnt++) { L1ItemInstance l1iteminstance1
		 * = player_tradelist.get(0);
		 * inv.tradeItem(l1iteminstance1,l1iteminstance1.getCount(),
		 * pc.getInventory()); } } inv = null; }
		 */
		// 終止決鬥
		try {
			if (pc.getFightId() != 0) {

				pc.setFightId(0);
				L1PcInstance fightPc = (L1PcInstance) L1World.getInstance()
						.findObject(pc.getFightId());
				if (fightPc != null) {
					fightPc.setFightId(0);
					fightPc.sendPackets(new S_PacketBox(S_PacketBox.MSG_DUEL,0, 0));
					fightPc = null;
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		/** 刪除副本通關道具(禁止帶出) */
		for (final L1ItemInstance item : pc.getInventory().getItems()) {
			if (item.getItem().getType() == 20) {
				pc.getInventory().tradeItem(item, item.getCount(), L1World.getInstance().getInventory(pc.getLocation()));
			}
		}
		// 解除登入狀態
		try {
			pc.setOnlineStatus(0);
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// _log.error("人物離開遊戲的處理-解除登入狀態");
		// 資料紀錄
		try {
			pc.save();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// _log.error("人物離開遊戲的處理-資料紀錄");
		// 背包紀錄
		try {
			pc.saveInventory();
			// _log.error("人物離開遊戲的處理-背包紀錄");
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// 人物登出
		try {
			pc.logout();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		// _log.error("人物離開遊戲的處理-人物登出");
	}

	private static void remove_pet(final L1PcInstance pc, final Object[] petList) {
		try {
			L1NpcInstance petObject;
			L1PetInstance pet;
			for (final Object obj : petList) {
				petObject = (L1NpcInstance) obj;
				if (petObject != null) {
					if (petObject instanceof L1PetInstance) {
						pet = (L1PetInstance) petObject;
						pet.stopFoodTimer(pet); // 停止飽食度計時
						pet.setDead(true);// 寵物認知
						pet.dropItem();
						pet.deleteMe();

					} else if (petObject instanceof L1SummonInstance) {
						((L1SummonInstance) petObject).deleteMe();
						// visiblePc.sendPackets(new S_SummonPack(summon,
						// visiblePc,false));
						// S_NewMaster packet = new S_NewMaster(summon);
						/*
						 * for (final L1PcInstance visiblePc :
						 * L1World.getInstance().getVisiblePlayer(summon)) { if
						 * (visiblePc.equals(pc)) { continue; }
						 * //visiblePc.sendPackets(packet);
						 * visiblePc.sendPackets(new S_SummonPack(summon,
						 * visiblePc,false)); }
						 */
					}
				}
			}
			// 清空 寵物 召喚獸 清單
			pc.getPetList().clear();
			petObject = null;
			pet = null;
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
	}
}
